<template>
  <a-form :model="formImport" layout="vertical" autocomplete="off">
    <a-form-item label="Parquet文件">
      <a-upload
        v-model:file-list="fileList"
        name="file"
        :maxCount="1"
        action="/api/v1/common/upload-file"
        :headers="headers"
        @change="handleChange"
      >
        <a-button>{{ $t("351") }}</a-button>
      </a-upload>
    </a-form-item>
    <a-form-item label="使用文件中的字段配置">
      <a-switch v-model:checked="formImport.forceFields"></a-switch>
    </a-form-item>
    <a-form-item label="列匹配方式">
      <a-radio-group
        v-model:value="formImport.matchFieldBy"
        :disabled="formImport.forceFields"
      >
        <a-radio-button value="tag">标记</a-radio-button>
        <a-radio-button value="display">显示顺序</a-radio-button>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="旧记录处理方式">
      <a-radio-group v-model:value="formImport.matchRecord">
        <a-radio-button value="keep">保持</a-radio-button>
        <a-radio-button value="clear">清空</a-radio-button>
      </a-radio-group>
    </a-form-item>
    <p style="margin-top: 8px">
      <a-button type="primary" @click="doImport" :loading="state.loading"
        >开始导入</a-button
      >
    </p>
  </a-form>
</template>
<script setup>
import { reactive, ref } from "vue";
import CommonDefine from "@/component/CommonDefine";
import { useI18n } from "vue-i18n";

const channel = CommonDefine.channel();
const { t } = useI18n();
const fileList = ref([]);
const headers = {
  authorization: `Bearer ${localStorage.getItem("token")}`,
};
const state = reactive({
  loading: false,
});
const formImport = reactive({});

const handleChange = (info) => {
  if (info.file.status === "done") {
    // console.log(info.file.response);
    CommonDefine.apiPostArm(
      `/api/v1/model/check-parquet/${info.file.response}`,
      null,
      (d) => {
        // console.log(d);
        CommonDefine.alert(`上传成功，字段数 ${d[1]} 记录数 ${d[0]}`);
        if (!CommonDefine.useful(formImport.files)) {
          formImport.files = [];
        }
        formImport.files.push(info.file.response);
      }
    );
  } else if (info.file.status === "error") {
    CommonDefine.alert(t("353", [info.file.name]));
  }
};

const doImport = () => {
  formImport.modelId = channel.selectedModel.modelId;
  state.loading = true;
  fetch("/api/v1/model/import-file", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${localStorage.getItem("token")}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(formImport),
  })
    .then((res) => res.json())
    .then((arm) => {
      CommonDefine.alert(JSON.stringify(arm.data));
      state.loading = false;
    })
    .catch((e) => {
      CommonDefine.axiosErrorHandler(e);
      state.loading = false;
    });
};
</script>
